package top.bug.blog.utils;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description ip2region 工具类
 */
public class Ip2RegionUtil {

    private static Searcher searcher;

    static {
        try {
            // 加载数据库文件为 byte[]
            ClassPathResource resource = new ClassPathResource("ip2region.xdb");
            InputStream is = resource.getInputStream();
            // 使用兼容方法
            byte[] dbBinStr = readAllBytes(is);
            is.close();
            searcher = Searcher.newWithBuffer(dbBinStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询 IP 地址的地理位置
     *
     * @param ip IP 地址
     * @return 格式：国家|区域|省份|城市|ISP
     */
    public static String getRegion(String ip) {
        try {
            return searcher.search(ip);
        } catch (Exception e) {
            return "未知";
        }
    }

    public static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int nRead;
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        return buffer.toByteArray();
    }

}
